package com.smarthealthcare.discharge.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.AlipayConfig;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.FileItem;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.smarthealthcare.common.annotation.Anonymous;
import com.smarthealthcare.cost.domain.Cost;
import com.smarthealthcare.cost.mapper.CostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AliPay {
    @Autowired
    private CostMapper costMapper;

    @Anonymous
    @RequestMapping("/pay")
    public String pay(String oid, String money) throws AlipayApiException {
//        应用私钥
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDND2lk702DfftXEVDFARg5xA7/C1OrtVAupH04O+XwrRM/VzTA0MmtuSCeRDRqSb6QUEf76MZVLVE7+r+ecb64mGDqVwvmSv5PdPrNjJK9vdACSBgjXSEmQgDCArijNcuS5ue1qu32cvdCVSKO2GSU/30WR3+H5bCrw8+RwNhD+7LbPFMq6TcaHM+rz9u5UcZH1t8cvgSUoGUrkq0WRlzwTTpbCNSdZXPwvRTkoRDkmsIqL/Bq/qPAHjz6FSpUAvPl8Bw9hbaJMem2WuqkE6Mdl3Hp4yLYh90C5HlNeBxdi5RINTuL9psJzCCBhOhfboO8OdQal11wVbm+4PPBZoT1AgMBAAECggEAejs6jrDaW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YMnB+cMFbRCQBM+vKwfQ99BZPYhw7TRTiqz1hwQycy5cEz8rUSZYCRaTOOLVqYVpOxihk9qv4MOifzy8eaDBr4gyxks3Zfnlb8K4vBgCxMj+3QldbN0HQcMw5bPZ35";
//        支付宝公钥
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzQ9pZO9Ng337VxFQxQEYOcQO/wtTq7VQLqR9ODvl8K0TP1c0wNDJrbkgnkQ0akm+kFBH++jGVS1RO/q/nnG+uJhg6lcL5kr+T3T6zYySvb3QAkgYI10hJkIAwgK4ozXLkubntart9nL3QlUijthklP99Fkd/h+Wwq8PPkcDYQ/uy2zxTKuk3GhzPq8/buVHGR9bfHL4ElKBlK5KtFkZc8E06WwjUnWVz8L0U5KEQ5JrCKi/wav6jwB48+hUqVALz5fAcPYW2iTHptlrqpBOjHZdx6eMi2IfdAuR5TXgcXYuUSDU7i/abCcwggYToX26DvDnUGpddcFW5vuDzwWaE9QIDAQAB";
//        创建支付配置对象
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000142625317");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
//        创建支付宝支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
//        支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        支付的商品详情模板
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
//        动态获取订单信息
        model.setOutTradeNo(oid);// 商户订单号，唯一
        //  根据oid来查询订单对应的金额和商品名称
        model.setTotalAmount(money);   //  金额
        model.setSubject("您的医疗消费单");//  商品名称
        //  固定
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);
        //  设置支付成功后的回调函数
        request.setReturnUrl("http://localhost:8888/returnUrl");

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }

    //  支付成功后的回调函数
    @Anonymous
    @RequestMapping("/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println("------回调");
        //  查询
        //  从request中获取商品单号
        String outTradeNo = request.getParameter("out_trade_no");
        System.out.println("商户支付单号：" + outTradeNo);
        //  调用支付宝接口，根据单号查询支付状态，如果成功则修改数据库中的订单状态为已支付，反之则不修改
        //  code -- 10000    ---成功
        String code = validate(outTradeNo);
//        System.out.println(code);
        if (code.equals("10000")) {
            //  更改费用表单中的数据状态值
            costMapper.updateByPatientId(Long.parseLong(outTradeNo));
        } else {
            // 处理错误情况
            // 设置错误状态码和消息
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500错误
        }
        //  给客户一个响应
//        return "success";

        //  如果是vue，则需要跳转到vue前端中的路由模式中
        response.sendRedirect("http://localhost:88/discharge-followup/discharge");
//        response.sendRedirect("http://localhost:88/cost/costList");
    }


    //  检测是否支付是否双方交易成功
    @Anonymous
    @RequestMapping("/validate")
    public String validate(String oid) throws AlipayApiException {
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDND2lk702DfftXEVDFARg5xA7/C1OrtVAupH04O+XwrRM/VzTA0MmtuSCeRDRqSb6QUEf76MZVLVE7+r+ecb64mGDqVwvmSv5PdPrNjJK9vdACSBgj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yUzuO3PsJJLbyn0XqUuPbtGFtL181CywKBgB3biCz46kOatfL7ioMnDcmTN8rd5h0KXD901/xRq4oWiK0OE31X/n8fklr/0yy+RZiuIlEBtKskVPbzjHd3o6ese+XUwh/IrjuZoxWzfniRhLVe7kDbiLJ5oLOXPfm7uAH8lXXWyQZj/9oEri+Si2UBR5BrbPC5sF74C6C4nDf3AoGBALd4pQH4crG8VD+RAnmH1l2h6VDdJrEMG4G5b9ci54DjPuYMnB+cMFbRCQBM+vKwfQ99BZPYhw7TRTiqz1hwQycy5cEz8rUSZYCRaTOOLVqYVpOxihk9qv4MOifzy8eaDBr4gyxks3Zfnlb8K4vBgCxMj+3QldbN0HQcMw5bPZ35";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu00/bpgkkUMvGXn2vgDRP7a4YLI89uz4In0G6d406xhPenPkCj43NjzWbBOgksPNalZFoSE6ECpqhdpJoDrhl3K6GjyvY4pcxRLKmP4DoblkfeMhmlWn6dKC/vHqUja8QVX5/lAkfUF4zp7WJKGa/zhnr/8O7qCmhgrX+hY/p/uycZT31WYzpsqzuOPttpRj/nVmn+nwae3S0fokfxDOG/ZqbTFMfBrUATrqeh3nSfbzmQsQTlitRiRf+nEAXGyB0M0H2+/wRUDDVK71llFSiNR8THdh1QcIFSpyYnn4jqjGEdrhtOFqG6zSIX3HkP+buEiq5VYj8xfSaS3bMjhOlQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000142625317");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(oid);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
        JSONObject jsonObject = (JSONObject) JSON.parse(response.getBody());
        JSONObject alipayTradeQueryResponse = jsonObject.getJSONObject("alipay_trade_query_response");
        System.out.println(alipayTradeQueryResponse.get("code"));   //获取返回值code
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return (String) alipayTradeQueryResponse.get("code");
    }
}